import { auth, buildMenu, info } from '@/api/auth'
import { registeredUserRoute } from '@/router/shared'
import { getToken, setToken } from '@/utils/token'
import { defineStore } from 'pinia'
import type { IUserInfo, IUserLogin } from '@/types'
import type { RouteRecordRaw } from 'vue-router'

interface IUserState {
  token: string | undefined;
  userInfo: IUserInfo | object;
  menuList: RouteRecordRaw[];
}

export const useUserStore = defineStore('user', {
  state (): IUserState {
    return {
      token: getToken(),
      userInfo: {},
      menuList: []
    }
  },
  actions: {
    async login (formInfo: IUserLogin) {
      const { token, user } = await auth(formInfo)
      setToken(token)
      this.token = token
      this.userInfo = user
      return await this.getBuildMenu(true)
    },
    async getUserInfo () {
      const user = await info()
      this.userInfo = user
      return await this.getBuildMenu()
    },
    async getBuildMenu (addRoutes = false) {
      const menuList = await buildMenu()
      this.menuList = menuList
      addRoutes && registeredUserRoute()
      return menuList
    }
  }
})
